package com.yymmarket.forum.bbs;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.whirlycott.cache.Cache;
import com.yymmarket.forum.cache.ForumCache;

public class ContentReplyService {

	private static ContentReplyService replyService;

	private ContentReplyService() {
	}

	public static ContentReplyService getInstance() {
		if (replyService == null) {
			synchronized (ContentReplyService.class) {
				if (replyService == null)
					replyService = new ContentReplyService();
			}
		}
		return replyService;
	}
	
	
	private ContentReplyDAO replyDao = new ContentReplyDAO();
	
	static Cache replyCache = ForumCache.replyCache;
	public boolean addReplyBean(ContentReplyBean bean) {
		boolean flag = this.replyDao.addReplyBean(bean);
		if(flag) {
			replyCache.store(bean.getId(), bean);
			ContentBean contentBean = ContentService.getInstance().getContentById(bean.getContentId());
			contentBean.getReplyIdList().add(bean.getId());
			
			contentBean.incrementReply();
			contentBean.setLastReplyTime(new Date());
			List<Integer> list = ContentService.getInstance().getContentsByBbsId(contentBean.getBbsId());
			list.remove(Integer.valueOf(contentBean.getId()));
			list.add(0,Integer.valueOf(contentBean.getId()));
		}
		
		return flag;
	}
	
	public ContentReplyBean getReplyBeanById(long id) {
		ContentReplyBean bean = (ContentReplyBean)replyCache.retrieve(id);
		
		if(bean == null) {
			bean = this.replyDao.getReplyBeanById(id);
			if(bean != null) {
				replyCache.store(id, bean);
			}
		}
		
		return bean;
	}
	
	/**
	 * @param contentId
	 * @return
	 */
	public List<Long> getReplysByContentId(int contentId,boolean asc) {
		return this.replyDao.getReplysByContentId(contentId,asc);
	}
	
	/**
	 * @deprecated to use the getReplyIdList method of ContentBean.class
	 * @param contentId
	 * @param start
	 * @param limit
	 * @return
	 */
	public List<ContentReplyBean> getReplysByContentId(int contentId,int start,int limit) {
		List<Long> list = this.replyDao.getReplysByContentId(contentId, start, limit);
		
		List<ContentReplyBean> replyList = new ArrayList<ContentReplyBean>();
		for (Long id : list) {
			replyList.add(this.getReplyBeanById(id));
		}
		return replyList;
	}
	
	public boolean deleteReplyByIdAndUid(long id, int uid) {
		
		ContentReplyBean bean = getReplyBeanById(id);
		
		boolean flag = false;
		
		if(bean == null) {
			return false;
		}
		
		flag = this.replyDao.deleteReplyByIdAndUid(id, uid);
		
		if(flag) {
			bean.setDeleteMark((short)1);
			bean.setDeleteUserId(uid);		
		}
		return flag;
	}
}
